<?php

namespace app\api\controller\paotui\poster;

use addons\paotui\service\Poster;
use app\admin\model\paotui\PosterLocation;
use think\Exception;
use think\Db;
use addons\shopro\service\order\OrderOper;
use app\admin\model\shopro\order\Order as OrderModel;
use addons\shopro\service\commission\Reward as RewardService;
use app\admin\model\shopro\commission\Order as CommissionOrderModel;

/**
 * 快递接口
 */
class Post extends PosterApi
{

    // 无需登录的接口,*表示全部
    protected $noNeedLogin = [];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = "*";

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 快递列表
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index(){
        $status = $this->request->post("type",'');  // 1待抢单 2待揽收 3运输中 4派送中 5已完成 6服务中（2,3,4） -1已取消
        $page = $this->request->post('page',0);
        $limit = $this->request->post('limit',0);
        
        $where['poster_id'] = $this->auth->id;

        //获取当前快递员的最近的经纬度
        $posterLocationModel = new PosterLocation();
        $posterLocationInfo = $posterLocationModel->where(['poster_id'=>$this->auth->id])->find();
        $lat = empty($posterLocationInfo['lat'])?0:$posterLocationInfo['lat'];
        $lng = empty($posterLocationInfo['lat'])?0:$posterLocationInfo['lng'];

        $postService = new \addons\paotui\service\Post();
        $data = $postService->getPosterPostList($status,$where,$page,$limit,"*",$lng,$lat,$this->auth->id);
        
        $this->success('请求成功',$data);
    }

    /**
     * 拒单
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function refuse(){
        $order_no = $this->request->post('order_no',"");
        $postService = new \addons\paotui\service\Post();
        if($postInfo =  $postService->getInfoByPoster($order_no,$this->auth->id)){
            \addons\paotui\service\Post::refusePost($postInfo['id'],$this->auth->id);
            $this->success("请求成功",$postInfo);
        }else{
            $this->error($postService->error);
        }
    }

    /**
     * 接受派单
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function accept(){
        $order_no = $this->request->post('order_no',"");
       
        $postService = new \addons\paotui\service\Post();
        if($postInfo =  $postService->getInfoByPoster($order_no,$this->auth->id)){
            $poster = $this->auth->getPoster();
            \addons\paotui\service\Post::acceptPost($postInfo['id'],$poster);
            $this->success("请求成功",$postInfo);
        }else{
            $this->error($postService->error);
        }
    }
    /**
     * 获取订单取件码arr
     */
    public function codearr(){
        $order_no = $this->request->post('order_no',"");
        $order = Db::name('paotui_post')->where(['order_no'=>$order_no])->find();
        if($order){
            $codes  = Db::name('partition_code')->where(['paotui_post_id'=>$order['id'],'error_type'=>0,'status'=>1])->where('poster_id is null')->select();
            foreach($codes as $k=>&$v){
                if($v['partition_id'] == 0){
                    $v['codes'] = '其他：'.$v['codes'];
                }else{
                    $partition = Db::name('partition')->where(['id'=>$v['partition_id']])->find();
                    $station = Db::name('station')->where(['id'=>$partition['station_id']])->find();
                   
                    $v['codes'] = $station['name'].'：'.$v['codes'];
                    
                }
            }
            $this->success("请求成功",$codes);
        }else{
            $this->error('没有要取的取件码');
        }
        // p($codes);die;
    }
    /**
     * 获取订单详情
     */
    public function info(){
        $order_no = $this->request->post('order_no',"");
        if(empty($order_no)){
            $this->error("参数异常");
        }

        $postService = new \addons\paotui\service\Post();
        if($postInfo =  $postService->getInfoByPoster($order_no,$this->auth->id)){
            $this->success("请求成功",$postInfo);
        }else{
            $this->error($postService->error);
        }
    }

    /**
     * 快递员抢单
     */
    public function beat(){
        $order_no = $this->request->post('order_no',"");
        $codeclick = $this->request->post('codeclick',"");
       
        if(empty($order_no)){
            $this->error("参数异常");
        }
        $poster = $this->auth->getPoster();
        if($poster['is_order'] == 0){
            $this->error('请先听单');
        }
        // p($poster);die;
        $postService = new \addons\paotui\service\Post();
        if($postService->beatPost($order_no,$poster,$codeclick)){
            $this->success("抢单成功");
        }else{
            $this->error($postService->error);
        }
    }

    /**
     * 取件
     */
    public function collect(){
        $order_no = $this->request->post('order_no',"");
        $images = $this->request->post('images');
        if(empty($order_no)){
            $this->error("参数异常");
        }
        $poster = $this->auth->getPoster();
        $postService = new \addons\paotui\service\Post();
        if($postService->collectPost($order_no,$poster,$images)){
            $this->success("取件成功");
        }else{
            $this->error($postService->error);
        }

    }
    /**
     * l揽收衣服
     */
    public function cloth(){
        $order_no = $this->request->post('order_no',"");
        $images = $this->request->post('images');
        $clothnum = $this->request->post('clothnum');
        if(empty($order_no)){
            $this->error("参数异常");
        }
        $poster = $this->auth->getPoster();
        $postService = new \addons\paotui\service\Post();
        if($postService->clothPost($order_no,$poster,$images,$clothnum)){
            $this->success("取件成功");
        }else{
            $this->error($postService->error);
        }

    }
    /**
     * 送达
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function reach(){
        
        $order_no = $this->request->post('order_no',"");
        $image = $this->request->post('image');

        $lnglat = $this->request->post('lnglat');
        if(empty($order_no)){
            $this->error("参数异常");
        }

        $poster = $this->auth->getPoster();

        $postService = new \addons\paotui\service\Post();
        
        if($postService->reachPost($order_no,$poster,$lnglat,$image)){
           
            //计算快递员佣金
            $posterService = new Poster();
            $posterService->brokerage($order_no);
            //给快递员送钱
            
            // // 给用户发短信
            
			$this->send_message_user($order_no);
            //送达处理关联商城订单 20240808 masks
			$ppost=db('paotui_post')->where('order_no',$order_no)->find();
			if($ppost['shopro_order_id']){
				$id=$ppost['shopro_order_id'];
				$user=db('user')->where('id',ppost['user_id'])->find();
				$order = OrderModel::paid()->where('user_id', $user['id'])->where('id', $id)->find();
				if($order){
					$order = Db::transaction(function () use ($order, $user) {
						$orderOper = new OrderOper();
						$order = $orderOper->confirm($order, [], $user, 'user');

						return $order;
					});
				}
			}
			//送达处理分销订单 20240810 masks
			$service = new RewardService('finish');
			$commissionOrders = collection(CommissionOrderModel::where('order_id', $ppost['id'])->where('tb_name','paotui_post')->select());
			$commissionOrders->each(function ($commissionOrder) use ($service) {
				$service->runCommissionRewardByOrder($commissionOrder);
			});
            
            $this->success("送达成功");
        }else{
            $this->error($postService->error);
        }
    }
    
    /**
     * 发送短信 给用户
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function send_message_user(){
        // 直接发送短信
        $order = $this->request->post('order_no',"");
      
        $config = get_addon_config('alisms');
        $order1 = Db::name('paotui_post')->where('order_no',$order)->find();
        if($order1['to_mobile']){
            $mobile = $order1['to_mobile'];
        }else{
            $usermob = Db::name('user_school')->where('id',$order1['to_address_id'])->find();
            $mobile = $usermob['phone'];
        }
            
            $template = $config['template']['deliver'];
            $sign = '';
            if (!$mobile || !$template) {
                $this->error('手机号、模板ID不能为空');
            }
            $sign = $sign ? $sign : $config['sign'];
            $param = (array)json_decode($this->request->post('param', '', 'trim'));
            // $param['code'] = '1111';
            $alisms = new \addons\alisms\library\Alisms();
            $ret = $alisms->mobile($mobile)
                ->template($template)
                ->sign($sign)
                ->param($param)
                ->send();
			// p($ret);
    	    
    	   if($ret){
    	       
    	       Db::name('paotui_post')->where(['order_no'=>$order])->update(['user_msg'=>1]);
    	       $this->success("短信发送成功");
    	       
    	   }else{
    	       $err = $err.','.$usermob['phone'].' '.$alisms->getError();
    	   }
        
            
    }
    /**
     * 骑手设置价格
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function reachPrice(){
        
        $order_no = $this->request->post('order_no',"");
        $price = $this->request->post('price'); 
        $image = $this->request->post('image'); 

        if(empty($order_no)){
            $this->error("参数异常");
        }

        $poster = $this->auth->getPoster();
		
		//首单判断 masks
		$data = Db::name('paotui_post')->where(['order_no'=>$order_no])->find();
		$type=$data['type'];
		$issd=0;
		$is1=Db::name('paotui_post')->where(['user_id'=>$data['user_id'],'type'=>$type])->order('createtime')->find();
		// echo Db::name('paotui_post')->getLastSql();
		if($is1['id']==$data['id']){
			$issd = 1;
		}
		$pp=$price;
		if($issd)$pp=0;
		// p($data);
		// p($pp);
		// p($is1);
		// die;
        //直接给订单状态1
        $post = Db::name('paotui_post')->where(['order_no'=>$order_no])->update(['total_price'=>$price,'images'=>$image,'pay_price'=>$pp,'updatetime'=>time(),'status'=>4]);
        if($post){
            $this->success("价格设置成功");
        }else{
            $this->error("价格设置失败");
        }
        // $this->error($postService->error);
       
    }
    /**
     * 骑手设置快递单号
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function ExpressNo(){
        
        $order_no = $this->request->post('order_no',"");
        $express_no = $this->request->post('express_no'); 

        if(empty($order_no)){
            $this->error("参数异常");
        }

        $poster = $this->auth->getPoster();
		
        //直接给订单状态1
        $post = Db::name('paotui_post')->where(['order_no'=>$order_no])->update(['express_no'=>$express_no,'updatetime'=>time(),'status'=>5]);
        if($post){
            $this->success("快递单号设置成功");
        }else{
            $this->error("快递单号设置失败");
        }
        // $this->error($postService->error);
       
    }
    /**
     * 骑手设置打包价格
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function packagePrice(){
        
        $order_no = $this->request->post('order_no',"");
        $price = $this->request->post('price'); 
        $image = $this->request->post('image'); 

        if(empty($order_no)){
            $this->error("参数异常");
        }

        $poster = $this->auth->getPoster();
		
		//首单判断 masks
		$data = Db::name('paotui_post')->where(['order_no'=>$order_no])->find();
		$type=$data['type'];
		$issd=0;
		$is1=Db::name('paotui_post')->where(['user_id'=>$data['user_id'],'type'=>$type])->order('createtime')->find();
		// echo Db::name('paotui_post')->getLastSql();
		if($is1['id']==$data['id']){
			$issd = 1;
		}
		$pp=$price;
// 		if($issd)$pp=0;
		// p($data);
		// p($pp);
		// p($is1);
		// die;
        //直接给订单状态1
        $post = Db::name('paotui_post')->where(['order_no'=>$order_no])->update(['total_price'=>$price,'reach_images'=>$image,'pay_price'=>$pp,'updatetime'=>time(),'status'=>4]);
        if($post){
            $this->success("价格设置成功");
        }else{
            $this->error("价格设置失败");
        }// $this->error($postService->error);
    }
    public function listen(){
        $po = $this->request->post();
        if($po){
            if($po['type'] == 0){
                
                $rx = Db::name('worktime')->where([ 'user_id'=>$this->auth->id])->where('endtime is null')->find();
                if(!$rx){
                    $this->error('时间错误，请联系工作人员');
                }
                $res = Db::name('worktime')->where([ 'id'=>$rx['id']])->update(['endtime'=>time()]);
                //工作人员表更新
                 Db::name('paotui_poster')->where(['id'=>$this->auth->id])->update(['last_offline_time'=>time(), 'is_order' => 0]);
                
            }else{
                $data = [
                    'user_id'=>$this->auth->id,
                    'createtime'=>time(),
                    'status'=>0
                ];
                $res = Db::name('worktime')->insert($data);
                 //工作人员表更新
                Db::name('paotui_poster')->where(['id'=>$this->auth->id])->update(['last_online_time'=>time(), 'is_order' => 1]);
            }
            
            if($res){
                $this->success('成功');
            }else{
                $this->error('参数错误');
            }
            
        }else{
            $this->error('参数错误');
        }
    }
    
    public function getlistenstatus(){
        $res = Db::name('worktime')->where(['user_id'=>$this->auth->id])->where('endtime is null')->find();
        if($res){
            $this->success('成功');
        }else{
             $this->error('没有');
        }
    }
    public function error_type(){
        $po = $this->request->post();
        
        //判断人员是否听单中
        // $work = Db::name('paotui_poster')->where(['id'=>$this->auth->id])->find();
        // if($work['is_order'] == 0){
        //     $this->error('请先听单');
        // }
        
        
        
        $res = Db::name('partition_code')->where(['id'=>$po['id']])->update(['error_type'=>$po['error_type'],'status'=>2,'taketime'=>time(),'take_user_id'=>$this->auth->id,'updatetime'=>time()]);
     
        if($res){
            $sts =   Db::name('partition_code')->where(['id'=>$po['id']])->find();
            //更新成功，判断订单状态
            $allcode = Db::name('partition_code')->where('canceltime',0)->where(['paotui_post_id'=>$sts['paotui_post_id']])->where(['status'=>0])->where('poster_id is null')->find();
            if(!$allcode){
                //判断订单是否全是异常
                $errcode = Db::name('partition_code')->where('canceltime',0)->where(['paotui_post_id'=>$sts['paotui_post_id']])->where(['error_type'=>0])->find();
                if($errcode){
                    $rx = Db::name('paotui_post')->where(['id'=>$sts['paotui_post_id']])->update(['status'=>2,'updatetime'=>time()]);
                }else{
                    $rx = Db::name('paotui_post')->where(['id'=>$sts['paotui_post_id']])->update(['pay_status'=>1,'status'=>-1,'updatetime'=>time()]);
                }
                
            }
            
            // $res = Db::name('partition_code')->where(['id'=>$po['id']])->find();
            //取件成功判断工作人员类型
		  //  $poster = Db::name('paotui_poster')->where(['id'=>$this->auth->id])->find();
		  //  if($poster['poster_type'] == 1){
		  //      //按个数计件
		  //      $price = $poster['money'] + $poster['brokerage_scale'];
		  //      Db::name('paotui_poster')->where(['id'=>$this->auth->id])->update(['money'=>$price,'updatetime'=>time()]);
		  //       //生成资金记录
		  //      $data = [
		  //          'poster_id'=>$this->auth->id,
		  //          'type'=>'order',
		  //          'source_id'=>$res['paotui_post_id'],
		  //          'money'=>$poster['brokerage_scale'],
		  //          'before'=>$poster['money'],
		  //          'after'=>$price,
		  //          'memo'=>'取件分佣',
		  //          'createtime'=>time()
		  //          ];
		  //      $recorde = Db::name('paotui_poster_money_log')->insert($data);   
		  //  }
		  //生成一条记录
		    $logdata = [
		        'post_id'=>$sts['paotui_post_id'],
		        'poster_id'=>$this->auth->id,
		        'poster_name'=>$poster['poster_name'],
		        'poster_mobile'=>$poster['mobile'],
		        'type'=>6,
		        'createtime'=>time(),
		        ];
		    $addlog = Db::name('paotui_post_order')->insert($logdata);   
            $this->success('成功');
        }
    }
}
